package com.first.nell.components.input

import android.annotation.SuppressLint
import android.content.Context
import android.util.AttributeSet
import android.view.View
import android.widget.RelativeLayout
import androidx.fragment.app.FragmentManager
import com.first.nell.R
import com.first.nell.base.BaseFormAction
import com.first.nell.databinding.ViewFirstNellLoginOtpInputBinding
import com.first.nell.extend.addFirstNellUnderFirstNellLine
import com.first.nell.extend.recordFirstNellTagFirstNellEvent
import com.first.nell.extend.toFirstNell00FirstNellFormat
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.*

class LoginOtpInput : RelativeLayout, BaseFormAction {

    lateinit var mFirstNellViewFirstNellBinding: ViewFirstNellLoginOtpInputBinding
    private lateinit var vFirstNellRootFirstNellView: View

    private var mFirstNellSupportFirstNellFragmentFirstNellManager: FragmentManager? = null
    private var mFirstNellCutdownFirstNellFlow: Job? = null

    private var mFirstNellOnFirstNellActionFirstNellClickFirstNellListener: (Int) -> Unit = {}
    private var mFirstNellOnFirstNellInputFirstNellCompletedFirstNellListener: (String) -> Unit =
        { text -> }

    constructor(context: Context?) : this(context, null)
    constructor(context: Context?, attrs: AttributeSet?) : this(context, attrs, 0)
    constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : this(
        context,
        attrs,
        defStyleAttr,
        0
    )

    @SuppressLint("Recycle")
    constructor(
        context: Context?,
        attrs: AttributeSet?,
        defStyleAttr: Int,
        defStyleRes: Int,
    ) : super(
        context,
        attrs,
        defStyleAttr,
        defStyleRes
    ) {
        context?.let {
            vFirstNellRootFirstNellView = View.inflate(it, R.layout.view_first_nell_login_otp_input, this)
            mFirstNellViewFirstNellBinding = ViewFirstNellLoginOtpInputBinding.bind(vFirstNellRootFirstNellView)
            initFirstNellSubviews()
        }
    }

    override fun initFirstNellSubviews() {
        try {
            mFirstNellViewFirstNellBinding.textLoginAccountOtpResend.addFirstNellUnderFirstNellLine()
            mFirstNellViewFirstNellBinding.textLoginAccountOtpResend.setOnClickListener {
                val gText = mFirstNellViewFirstNellBinding.textLoginAccountOtpResend.text.toString().trim()
                if (gText.contains(context.getString(R.string.first_nell_resend))) {
                    mFirstNellOnFirstNellActionFirstNellClickFirstNellListener.invoke(0)
                    //记录打点
                    mFirstNellViewFirstNellBinding.textLoginAccountOtpCutdown.recordFirstNellTagFirstNellEvent()
                }
            }
        } catch (e: java.lang.Exception) {
            e.printStackTrace()
        }
    }

    private fun initFirstNellCutdownFirstNellFlow(
        scope: CoroutineScope,
        onTick: (Int) -> Unit,
        onFinish: () -> Unit,
    ): Job {
        return flow {
            for (tickSec in 60 downTo 0) {
                emit(tickSec)
                if (tickSec != 0) {
                    delay(1000)
                }
            }
        }.flowOn(Dispatchers.Main)
            .onEach { onTick.invoke(it) }
            .onCompletion { onFinish.invoke() }
            .launchIn(scope)
    }

    fun setFirstNellDelete() {
        val otp1 = mFirstNellViewFirstNellBinding.textLoginOtp1.text.toString().trim()
        val otp2 = mFirstNellViewFirstNellBinding.textLoginOtp2.text.toString().trim()
        val otp3 = mFirstNellViewFirstNellBinding.textLoginOtp3.text.toString().trim()
        val otp4 = mFirstNellViewFirstNellBinding.textLoginOtp4.text.toString().trim()

        if (otp4.isNotBlank()) {
            mFirstNellViewFirstNellBinding.textLoginOtp4.text = ""
            mFirstNellViewFirstNellBinding.textLoginOtp4.setBackgroundResource(R.drawable.first_nell_otp_input_not_fill)

        } else if (otp3.isNotBlank()) {
            mFirstNellViewFirstNellBinding.textLoginOtp3.text = ""
            mFirstNellViewFirstNellBinding.textLoginOtp3.setBackgroundResource(R.drawable.first_nell_otp_input_not_fill)

        } else if (otp2.isNotBlank()) {
            mFirstNellViewFirstNellBinding.textLoginOtp2.text = ""
            mFirstNellViewFirstNellBinding.textLoginOtp2.setBackgroundResource(R.drawable.first_nell_otp_input_not_fill)

        } else if (otp1.isNotBlank()) {
            mFirstNellViewFirstNellBinding.textLoginOtp1.text = ""
            mFirstNellViewFirstNellBinding.textLoginOtp1.setBackgroundResource(R.drawable.first_nell_otp_input_not_fill)
        }
    }

    fun setFirstNellNextFirstNellOTP(content: String) {
        if (content.isNotBlank()) {
            val otp1 = mFirstNellViewFirstNellBinding.textLoginOtp1.text.toString().trim()
            val otp2 = mFirstNellViewFirstNellBinding.textLoginOtp2.text.toString().trim()
            val otp3 = mFirstNellViewFirstNellBinding.textLoginOtp3.text.toString().trim()
            val otp4 = mFirstNellViewFirstNellBinding.textLoginOtp4.text.toString().trim()
            if (otp1.isBlank()) {
                mFirstNellViewFirstNellBinding.textLoginOtp1.text = content.substring(0, 1)
                mFirstNellViewFirstNellBinding.textLoginOtp2.text = ""
                mFirstNellViewFirstNellBinding.textLoginOtp3.text = ""
                mFirstNellViewFirstNellBinding.textLoginOtp4.text = ""

                mFirstNellViewFirstNellBinding.textLoginOtp1.setBackgroundResource(R.drawable.first_nell_otp_input_fill)

            } else if (otp2.isBlank()) {
                mFirstNellViewFirstNellBinding.textLoginOtp2.text = content.substring(0, 1)
                mFirstNellViewFirstNellBinding.textLoginOtp3.text = ""
                mFirstNellViewFirstNellBinding.textLoginOtp4.text = ""

                mFirstNellViewFirstNellBinding.textLoginOtp2.setBackgroundResource(R.drawable.first_nell_otp_input_fill)

            } else if (otp3.isBlank()) {
                mFirstNellViewFirstNellBinding.textLoginOtp3.text = content.substring(0, 1)
                mFirstNellViewFirstNellBinding.textLoginOtp4.text = ""

                mFirstNellViewFirstNellBinding.textLoginOtp3.setBackgroundResource(R.drawable.first_nell_otp_input_fill)

            } else if (otp4.isBlank()) {
                mFirstNellViewFirstNellBinding.textLoginOtp4.text = content.substring(0, 1)
                mFirstNellOnFirstNellInputFirstNellCompletedFirstNellListener.invoke(getFirstNellContent())

                mFirstNellViewFirstNellBinding.textLoginOtp4.setBackgroundResource(R.drawable.first_nell_otp_input_fill)
            }
        }
    }

    fun getFirstNellContent(): String {
        val otp1 = mFirstNellViewFirstNellBinding.textLoginOtp1.text.toString().trim()
        val otp2 = mFirstNellViewFirstNellBinding.textLoginOtp2.text.toString().trim()
        val otp3 = mFirstNellViewFirstNellBinding.textLoginOtp3.text.toString().trim()
        val otp4 = mFirstNellViewFirstNellBinding.textLoginOtp4.text.toString().trim()

        if (otp1.isBlank() or otp2.isBlank() or otp3.isBlank() or otp4.isBlank()) {
            return ""
        }
        return (otp1 + otp2 + otp3 + otp4)
    }

    fun isFirstNellCompleted(): Boolean {
        val otp1 = mFirstNellViewFirstNellBinding.textLoginOtp1.text.toString().trim()
        val otp2 = mFirstNellViewFirstNellBinding.textLoginOtp2.text.toString().trim()
        val otp3 = mFirstNellViewFirstNellBinding.textLoginOtp3.text.toString().trim()
        val otp4 = mFirstNellViewFirstNellBinding.textLoginOtp4.text.toString().trim()
        if (otp1.isBlank()) {
            mFirstNellViewFirstNellBinding.textLoginOtp1.setBackgroundResource(R.drawable.first_nell_otp_input_error)
        } else {
            mFirstNellViewFirstNellBinding.textLoginOtp1.setBackgroundResource(R.drawable.first_nell_otp_input_fill)
        }

        if (otp2.isBlank()) {
            mFirstNellViewFirstNellBinding.textLoginOtp2.setBackgroundResource(R.drawable.first_nell_otp_input_error)
        } else {
            mFirstNellViewFirstNellBinding.textLoginOtp2.setBackgroundResource(R.drawable.first_nell_otp_input_fill)
        }

        if (otp3.isBlank()) {
            mFirstNellViewFirstNellBinding.textLoginOtp3.setBackgroundResource(R.drawable.first_nell_otp_input_error)
        } else {
            mFirstNellViewFirstNellBinding.textLoginOtp3.setBackgroundResource(R.drawable.first_nell_otp_input_fill)
        }

        if (otp4.isBlank()) {
            mFirstNellViewFirstNellBinding.textLoginOtp4.setBackgroundResource(R.drawable.first_nell_otp_input_error)
        } else {
            mFirstNellViewFirstNellBinding.textLoginOtp4.setBackgroundResource(R.drawable.first_nell_otp_input_fill)
        }

        if (otp1.isBlank() or otp2.isBlank() or otp3.isBlank() or otp4.isBlank()) {
            return false
        }

        return true
    }

    fun isFirstNellCompletedFirstNellSlient(): Boolean {
        val gcontent = getFirstNellContent()
        if (gcontent.isBlank()) {
            return false
        }
        return true
    }

    @SuppressLint("SetTextI18n")
    fun startFirstNellCutdown(scope: CoroutineScope) {
        mFirstNellViewFirstNellBinding.textLoginAccountOtpCutdownDes.visibility = VISIBLE
        mFirstNellViewFirstNellBinding.textLoginAccountOtpCutdown.visibility = VISIBLE
        mFirstNellViewFirstNellBinding.textLoginAccountOtpResend.visibility = GONE
        mFirstNellCutdownFirstNellFlow = initFirstNellCutdownFirstNellFlow(scope,
            {
                if (it == 0) {
                    mFirstNellCutdownFirstNellFlow?.cancel()
                }
                mFirstNellViewFirstNellBinding.textLoginAccountOtpCutdown.text =
                    "(${it.toFirstNell00FirstNellFormat()}s)"
            },
            {
                mFirstNellViewFirstNellBinding.textLoginAccountOtpCutdownDes.visibility = GONE
                mFirstNellViewFirstNellBinding.textLoginAccountOtpCutdown.visibility = GONE
                mFirstNellViewFirstNellBinding.textLoginAccountOtpResend.visibility = VISIBLE
            })
    }

    fun stopFirstNellCutdown() {
        mFirstNellCutdownFirstNellFlow?.cancel()
    }

    override fun setFirstNellFragmentFirstNellManager(manager: FragmentManager) {
        mFirstNellSupportFirstNellFragmentFirstNellManager = manager
    }

    override fun setFirstNellOnFirstNellActionFirstNellClickFirstNellListener(listener: (Int) -> Unit) {
        mFirstNellOnFirstNellActionFirstNellClickFirstNellListener = listener
    }

    override fun setFirstNellTitle(title: String) {

    }

    override fun setFirstNellDetail(detail: String) {

    }

    override fun setFirstNellContent(content: String) {

    }

    override fun setFirstNellHint(hint: String) {

    }

    override fun setFirstNellDetailFirstNellColor(detailColor: Int) {

    }

    override fun setFirstNellTitleFirstNellColor(titleColor: Int) {

    }

    fun setFirstNellOnFirstNellInputFirstNellCompletedFirstNellListener(listener: (String) -> Unit) {
        mFirstNellOnFirstNellInputFirstNellCompletedFirstNellListener = listener
    }
}